package service.impl;

import constant.Constant;
import dao.UserDao;
import entity.User;
import exception.DuplicateUsernameException;
import exception.UserDisabledException;
import exception.UserNotFoundException;
import framework.bean.factory.ObjectFactory;
import framework.bean.factory.annotation.Component;
import service.UserService;
import util.MD5Util;

import java.util.Date;

@Component("userServiceTarget")
public class UserServiceImpl implements UserService {

    @Override
    public void regist(User user) throws DuplicateUsernameException {
        UserDao userDao= (UserDao) ObjectFactory.getObject("userDao");

        User u=userDao.selectByUsername(user.getUsername());

        if(u!=null){
            throw new DuplicateUsernameException("用户名已存在");
        }

        user.setRegistDate(new Date());

        user.setPassword(MD5Util.md5(user.getPassword()));

        user.setStatus(Constant.UserStatus.USER_STATAUS_ENABLE);

        userDao.insert(user);
    }

    @Override
    public User login(String username, String password) throws UserNotFoundException, UserDisabledException {
        UserDao userDao= (UserDao) ObjectFactory.getObject("userDao");

        User user=userDao.selectByUsernameAndPassword(username,MD5Util.md5(password));

        if(user==null){
            throw new UserNotFoundException("用户名或密码错误");
        }

        if(Constant.UserStatus.USER_STATUS_DISABLE.equals(user.getStatus())){
            throw new UserDisabledException("用户已被禁用");
        }

        return user;
    }

    @Override
    public void validateUsername(String username) throws DuplicateUsernameException {
        UserDao userDao= (UserDao) ObjectFactory.getObject("userDao");

        User user=userDao.selectByUsername(username);

        if(user!=null){
            throw new DuplicateUsernameException("用户名已存在");
        }
    }
}

















